# !/usr/bin/env python
# coding:utf-8


import time
import grpc
import numpy as np
import logging

import question_pb2_grpc, question_pb2
import contest_pb2_grpc, contest_pb2


CONTEST_HOST = '47.100.97.93'
CONTEST_PORT = '40723'

QUESTION_HOST = "47.100.97.93"
QUESTION_PORT = "40722"


class TradingBot(object):

    USER_ID = 43
    USER_PIN = "bT3ZGrIwOb"
    CHANNEL_LOGIN_SUBMIT = grpc.insecure_channel(target=CONTEST_HOST + ":" + CONTEST_PORT)
    CHANNEL_GETDATA = grpc.insecure_channel(target=QUESTION_HOST + ":" + QUESTION_PORT)

    stub_contest = contest_pb2_grpc.ContestStub(CHANNEL_LOGIN_SUBMIT)
    stub_question = question_pb2_grpc.QuestionStub(CHANNEL_GETDATA)

    def __init__(self):
        # 记录日志
        self.log = self.log_func()

        # login
        self.session_key = None
        self.login_success = None
        self.init_capital = None

        # 登录
        self.login()

        # 记录行情数据
        self.sequence = 0
        self.has_next_question = None
        self.capital = None
        self.dailystk = None
        self.positions = None

        # random positions
        self.is_initialized = False

        # submit
        self.accepted = None
        self.submit_pos = None

        # 调仓周期
        self.scheduler = 5

    def log_func(self):
        logger = logging.getLogger('log')
        logger.setLevel(logging.DEBUG)
        fh = logging.FileHandler(r'E:\九坤量化联赛第四届第四期\Q_quant\log\log_info.log')
        fh.setLevel(logging.INFO)
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        fh.setFormatter(formatter)
        logger.addHandler(fh)
        return logger

    def login(self):
        response = self.stub_contest.login(contest_pb2.LoginRequest(user_id=self.USER_ID,
                                                                    user_pin=self.USER_PIN))
        self.session_key = response.session_key
        self.init_capital = response.init_capital
        try:
            if response.success:
                self.log.info("登录成功>>")
        except Exception as e:
            self.log.info("登录失败>> %s" % e)

    def question(self):
        try:
            response_question = self.stub_question.get_question(question_pb2.QuestionRequest(user_id=self.USER_ID,
                                                                                             user_pin=self.USER_PIN,
                                                                                             sequence=self.sequence))
            if response_question.has_next_question:
                self.sequence = response_question.sequence
                self.has_next_question = response_question.has_next_question
                self.capital = response_question.capital
                self.dailystk = response_question.dailystk
                self.positions = response_question.positions
        except Exception as e:
            self.log.info("行情查询失败>> %s" % e)

    def strategy(self):
        if not self.is_initialized:
            self.submit_pos = np.random.randint(low=-2, high=3, size=(500,))
            return
        else:
            pass

    def submit(self):
        response_ansr = self.stub_contest.submit_answer(contest_pb2.AnswerRequest(
            user_id=self.USER_ID,
            user_pin=self.USER_PIN,
            session_key=self.session_key,
            sequence=self.sequence,
            positions=self.submit_pos
        ))

        if not response_ansr.accepted:
            self.log.info("报单未接受：%s" % response_ansr.reason)
        else:
            self.log.info("订单发送成功: %s" % response_ansr.accepted)

    def rock_and_roll(self):
        pre_count = self.sequence
        next_count = 0
        try:
            while True:
                time.sleep(0.1)
                self.question()
                next_count = self.sequence
                if next_count - pre_count >= self.scheduler:
                    self.strategy()
                    self.submit()
                    pre_count = next_count

        except KeyboardInterrupt:
            return


if __name__ == '__main__':
    trading_bot = TradingBot()
    trading_bot.rock_and_roll()
















